//
//  RMMTaoCanConfirmViewController.m
//  Romomo
//
//  Created by puman on 2016/12/29.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMTaoCanConfirmViewController.h"
#import "RMMConfirmOrderView.h"
#import "RMMPayOrderTableViewCell.h"
#import "RMMHuiYuanKaPayTableViewCell.h"
#import "RMMChongZhiViewController.h"
#import "RMMTaoCanConfirmTableViewCell.h"
#import "RMMTaoCanOrderDetailsViewController.h"
#import "RMMPayJieGuoViewController.h"
#import "RMMTuiJianRenViewController.h"

@interface RMMTaoCanConfirmViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMTaoCanConfirmViewController
{
    UITableView *_tableView;
    RMMPayFailureView *_backView;
    RMMPayResultView *_resultView;
    RMMNotNetWorkView *_networkView;
    RMMConfirmOrderView *_confirmView;
    NSArray *_imageNameArr;
    NSArray *_titleArr;
    NSMutableDictionary *_statDic;
    NSInteger _count;
    CGFloat _price;
    BOOL _isSuccess;
    NSString *_par_way_code;
    NSString *_tuiJianName;
    NSString *_emp_id;
    UILabel *_label;
    NSString *_emp_name;
    NSString *_balance;
    NSString *_yuE;
    NSString *_titleName;
    NSString *_desTitleName;
}
- (void)dealloc {
    NS_REM(@"PAYJIEGUOFUWU", [RMMFileManager shareHandle].payTypeName);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kCColor;
    self.navigationItem.title = @"确认订单";
    [self addSubViews];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getMemberBalance];
}
- (void)addSubViews{
    _yuE = @"0";
    _balance = @"0";
    _isSuccess = YES;
    _tuiJianName = @"推荐人(可不选)";
    _emp_id = @"";
    _emp_name = @"";
    _statDic = [NSMutableDictionary dictionary];
    _count = 1;
    _price = [_dic[@"PROD_BOM"][@"PRICE"] floatValue];
    _imageNameArr = @[@"微信支付@3x",@"支付宝@3x"];
    _titleArr = @[@"微信支付",@"支付宝支付"];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64 - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    [_tableView registerClass:[RMMTaoCanConfirmTableViewCell class] forCellReuseIdentifier:@"TaoCanCell"];
    [_tableView registerClass:[RMMHuiYuanKaPayTableViewCell class] forCellReuseIdentifier:@"carCell"];
    [_tableView registerClass:[RMMPayOrderTableViewCell class] forCellReuseIdentifier:@"PayCell"];
    [self.view addSubview:_tableView];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    
    _confirmView = [[RMMConfirmOrderView alloc] initWithFrame:CGRectMake(0, _tableView.bottom, kScreenWideth, 49)];
    _confirmView.totalPrice.text = [NSString stringWithFormat:@"¥%.2f",_price * _count];
    [_confirmView.confirmOderBut setTitle:@"确定支付" forState:(UIControlStateNormal)];
    BUTTON_S(_confirmView.confirmOderBut, confirmOderButclick);
    [self.view addSubview:_confirmView];
    [self cannotPay];
    
    _resultView = [[RMMPayResultView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _resultView.hidden = YES;
    BUTTON_S(_resultView.doneBut, doneButClick);
    [self.view addSubview:_resultView];
    
    _backView = [[RMMPayFailureView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_backView.backHomeBut, backHomeButClick:);
    BUTTON_S(_backView.goonPayBut, backHomeButClick:);
    _backView.hidden = YES;
    [self.view addSubview:_backView];
    
    _label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, kScreenWideth - 115, 40)];
    _label.font = kFont(16);
    _label.textColor = kBasicColor;
    _label.textAlignment = NSTextAlignmentRight;
    
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, networkBut);
    [self.view addSubview:_networkView];

}
- (void)networkBut{
    [self getMemberBalance];
}
//  会员卡余额
- (void)getMemberBalance{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    parDic[@"cust_id"] = cust_id;
    parDic[@"org_no"] = Org_no;
    NSString *url = GetCustCardUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
        if (isNetwork) {
            _networkView.hidden = YES;
        } else {
            _networkView.hidden = NO;
        }
    } method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _balance = [NSString stringWithFormat:@"%.2f",[dataDic[@"data"][@"BALANCE"] floatValue]];
            _yuE = [NSString stringWithFormat:@"%@元", _balance];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return _titleArr.count;
    } else {
        return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NSArray *array = _dic[@"PROD_SERVICES"];
        return 70 + 20 * array.count;
    } else if (indexPath.section == 1) {
        return 100;
    }  else {
        return 60;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 40)];
        view.backgroundColor = kCColor;
        
        
        UILabel *labelA = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, view.width - 30, view.height)];
        labelA.text = @"购买护理疗程";
        labelA.font = kFont(13);
        labelA.textColor = COLORFROMCODE(0x9B9B9B1, 1);
        [view addSubview:labelA];
        
        return view;
    } else if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 10)];
        view.backgroundColor = kCColor;
        return view;
    } else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 40)];
        view.backgroundColor = kCColor;
        UILabel *labelA = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, view.width - 30, view.height)];
        labelA.font = kFont(13);
        labelA.textColor = COLORFROMCODE(0x9B9B9B1, 1);
        [view addSubview:labelA];
        if (section == 2) {
            labelA.text = @"推荐支付方式(优惠套餐不参与支付折扣)";
            [RMMFileManager changeLabelTextColorOneWithLabel:labelA forRange:NSMakeRange(6, labelA.text.length - 6) byColor:COLORFROMCODE(0xF39805, 1)];
        } else {
            labelA.text = @"其他支付方式";
        }
        return view;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 10;
    }
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        RMMTaoCanConfirmTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TaoCanCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dic = _dic;
        cell.countLabel.text = [NSString stringWithFormat:@"%ld",_count];
        BUTTON_S(cell.subBut, subButClick:);
        BUTTON_S(cell.addBut, addButClick:);
        if (_count == 1) {
            [cell.subBut setImage:[UIImage imageNamed:@"un-subtract@3x"] forState:(UIControlStateNormal)];
            cell.subBut.userInteractionEnabled = NO;
        } else {
            [cell.subBut setImage:[UIImage imageNamed:@"subtract@3x"] forState:(UIControlStateNormal)];
            cell.subBut.userInteractionEnabled = YES;
        }

        return cell;

    }  else if (indexPath.section == 1) {
        RMMHuiYuanKaPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"carCell"];
        cell.balance = _yuE;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        BUTTON_S(cell.chongZhiBut, chongZhiButClick);
        BUTTON_S(cell.selcetBut, carSelcetBut:);
        cell.selcetBut.tag = 2;
        return cell;
    } else {
        RMMPayOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PayCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleName = _titleArr[indexPath.row];
        cell.imageName = _imageNameArr[indexPath.row];
        cell.selcetBut.userInteractionEnabled = NO;
       // BUTTON_S(cell.selcetBut, selcetButPayType:);
        cell.selcetBut.tag = 3 + indexPath.row;
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 1) {
//        RMMTuiJianRenViewController *VC = [[RMMTuiJianRenViewController alloc] init];
//        VC.blockTuiJianRen = ^void(NSDictionary *dic) {
//            _tuiJianName = [NSString stringWithFormat:@"推荐人"];
//            _emp_id = [NSString stringWithFormat:@"%@",dic[@"EMP_ID"]];
//            _emp_name = dic[@"EMPLOYEE_NAME"];
//            [_tableView reloadData];
//        };
//        [self.navigationController pushViewController:VC animated:YES];
//    } else if (indexPath.section == 2) {
//        [self selcetButPayType:indexPath.row];
//    }
    if (indexPath.section == 2) {
        [self selcetButPayType:indexPath.row];
    }
}
- (void)subButClick:(UIButton *)button{
    _count -= 1;
    _confirmView.totalPrice.text = [NSString stringWithFormat:@"¥%.2f",_price * _count];
    [_tableView reloadData];
}
- (void)addButClick:(UIButton *)button{
    if (_count == 99) {
        [RMMFileManager MBProgressWith:@"数量上限!" onView:self.view];
        return;
    }
    _count += 1;
    _confirmView.totalPrice.text = [NSString stringWithFormat:@"¥%.2f",_price * _count];
    [_tableView reloadData];
}

// 去充值
- (void)chongZhiButClick{
    RMMChongZhiViewController *VC = [[RMMChongZhiViewController alloc] init];
    VC.balance = _balance;
    [self.navigationController pushViewController:VC animated:YES];
}
// 选择支付方式
- (void)selcetButPayType:(NSInteger)row{
    UIButton *but = [self.view viewWithTag:2];
    UIButton *button = [self.view viewWithTag:row + 3];
    [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:but.tag]];
    [but setImage:[UIImage imageNamed:@"不可选@3x"] forState:(UIControlStateNormal)];
    NSNumber *stat = [_statDic objectForKey:[NSNumber numberWithInteger:button.tag]];
    for (int i = 0; i < _titleArr.count; i++) {
        UIButton *buttons = [self.view viewWithTag:3 + i];
        if (buttons.tag ==button.tag) {
            if ([stat isEqualToNumber:@1]) {
                [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:button.tag]];
                [button setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
                [self cannotPay];
            } else {
                [_statDic setObject:@1 forKey:[NSNumber numberWithInteger:button.tag]];
                [button setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
                [self canPay];
            }
            
        } else {
            [buttons setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
            [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:buttons.tag]];
        }
    }
    [_tableView reloadData];
}
- (void)carSelcetBut:(UIButton *)button{
    NSNumber *stat = [_statDic objectForKey:[NSNumber numberWithInteger:button.tag]];
    if ([stat isEqualToNumber:@1]) {
        [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:button.tag]];
        [button setImage:[UIImage imageNamed:@"不可选@3x"] forState:(UIControlStateNormal)];
        [self cannotPay];
        
    } else {
        [_statDic setObject:@1 forKey:[NSNumber numberWithInteger:button.tag]];
        [button setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
        [self canPay];
    }
    for (int i = 0; i < _titleArr.count; i++) {
        UIButton *buttons = [self.view viewWithTag:3+ i];
        [buttons setImage:[UIImage imageNamed:@"可选@3x"] forState:(UIControlStateNormal)];
        [_statDic setObject:@0 forKey:[NSNumber numberWithInteger:buttons.tag]];
    }
    [_tableView reloadData];
}
// 可以支付
- (void)canPay{
    _confirmView.confirmOderBut.backgroundColor = kBasicColor;
    [_confirmView.confirmOderBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    _confirmView.confirmOderBut.userInteractionEnabled = YES;
}
// 不可以支付
- (void)cannotPay{
    _confirmView.confirmOderBut.backgroundColor = RGBA(237, 238, 239, 1);
    [_confirmView.confirmOderBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
    _confirmView.confirmOderBut.userInteractionEnabled = NO;
    
}
- (void)confirmOderButclick{
    [RMMFileManager shareHandle].payTypeName = @"购买套餐";
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = cust_id;
    parDic[@"bom_id"] = _dic[@"PROD_BOM"][@"BOM_ID"];
    parDic[@"period"] = _orderDic[@"PERIODTIME"];
    parDic[@"order_id"] = _orderDic[@"ORDER_ID"];
    parDic[@"region_id"] = [RMMFileManager shareHandle].region_id;
    for (NSNumber *key in _statDic) {
        NSNumber *value = _statDic[key];
        if ([value isEqualToNumber:@1]) {
            if ([key isEqualToNumber:@2]) {
                // 会员卡支付
                _par_way_code = @"5";
            } else if ([key isEqualToNumber:@6]) {
                // 找朋友代付
                _par_way_code = @"";
                [RMMFileManager MBProgressWith:@"抱歉,支付方式暂不支持!" onView:self.view];
                return;
            } else if ([key isEqualToNumber:@3]) {
                // 微信支付
                _par_way_code = @"7";
            } else if ([key isEqualToNumber:@4]) {
                // 支付宝支付
                _par_way_code = @"8";
            } else {
                return;
            }
        }
    }
    parDic[@"pay_way_code"] = _par_way_code;
    parDic[@"payment"] = [NSString stringWithFormat:@"%.2f",_price * _count];
    parDic[@"masseur"] = _emp_id;
    parDic[@"buycount"] = [NSString stringWithFormat:@"%ld",_count];
    NSString *url = BuyTaoCanUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self beginPay];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];

}
- (void)beginPay{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"order_no"] = _orderDic[@"ORDER_NO"];
    parDic[@"atm"] = [NSString stringWithFormat:@"%.2f",_price * _count];
    NSString *url = @"";
    if ([_par_way_code isEqualToString:@"5"]) {
        [self paySuccess];
        return;
    } else if ([_par_way_code isEqualToString:@"7"]) {
        // 微信支付
        url = WeChatPayUrl;
    } else if ([_par_way_code isEqualToString:@"8"]) {
        // 支付宝支付
        url = GetALiPaySignUrl;
    } else {
        
    }
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NS_ADD(payJieGuo:, @"PAYJIEGUOFUWU", @"购买套餐");
            if ([_par_way_code isEqualToString:@"5"]) {
                // 会员卡
            } else if ([_par_way_code isEqualToString:@"7"]) {
                // 微信
                [self wechatPayWith:dataDic];
            } else if ([_par_way_code isEqualToString:@"8"]) {
                // 支付宝
                [self aLipayWith:[RMMPayManager backSingWithDic:dataDic[@"data"]]];
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];
}
// 微信支付
- (void)wechatPayWith:(NSDictionary *)dataDic{
    NSDictionary *dic = dataDic[@"data"];
    PayReq *request = [[PayReq alloc] init];
    request.partnerId                 = dic[@"partnerid"];
    request.prepayId                  = dic[@"prepayid"];
    request.package                   = dic[@"package"];
    request.nonceStr                  = dic[@"noncestr"];
    request.sign                      = dic[@"sign"];
    request.timeStamp                 = [dic[@"timestamp"] doubleValue];
    [WXApi sendReq:request];
}

- (void)payJieGuo:(NSNotification *)notification{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
    if([notification.object isEqualToString:@"购买套餐"]){
        NSDictionary *dic = [notification userInfo];
        if ([_par_way_code isEqualToString:@"5"]) {
            // 会员卡
        } else if ([_par_way_code isEqualToString:@"7"]) {
            // 微信
            NSString *type = dic[@"type"];
            if ([type isEqualToString:@"成功"]) {
                [self paySuccess];
            } else {
                [self payFailure];
                _backView.titleName = @"失败";
            }
        } else if ([_par_way_code isEqualToString:@"8"]) {
            // 支付宝
            NSString *status = dic[@"resultStatus"];
            if ([status isEqualToString:@"9000"]) {
                // 支付成功
                [self paySuccess];
            } else {
                [self payFailure];
                _backView.titleName = dic[@"memo"];
            }
        }
    }
}
- (void)aLipayWith:(NSString *)sign{
        [[AlipaySDK defaultService] payOrder:sign fromScheme:ALiPaySchemes callback:^(NSDictionary *resultDic) {
            // 如果支付结果
            NSLog(@"reslut = %@",resultDic);
        }];
}
// 支付成功
- (void)paySuccess{
    NS_POST(@"BIANJIDIZHI", nil, nil);
    // 支付成功
    if (_isSuccess) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
        _isSuccess = NO;
        _resultView.hidden = NO;
        _resultView.titelName = @"购买套餐";
        _resultView.price = [NSString stringWithFormat:@"%.2f",_price * _count];
        _backView.hidden = YES;
        self.navigationItem.title = @"支付结果";
        [RMMFileManager shareHandle].thred = @"1";
        NS_POST(@"ORDERUPDATA", nil, nil);
        NS_POST(@"SHOPFRESH", nil, nil);
    }
}
- (void)payFailure{
    // 支付失败
    // [RMMFileManager MBProgressWith:dic[@"memo"] onView:self.view];
    _resultView.hidden = YES;
    _backView.hidden = NO;
    self.navigationItem.title = @"支付结果";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:nil];
}

- (void)doneButClick{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)backHomeButClick:(UIButton *)button{
    if (button == _backView.backHomeBut) {
        NS_POST(@"SHOPFRESH", nil, nil);
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        [self confirmOderButclick];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
